//
// Created by 33145 on 2023/5/28.
//

#ifndef ROCKET_EVENTLOOP_H
#define ROCKET_EVENTLOOP_H

#include <pthread.h>
#include <set>
#include <functional>
#include <queue>

#include "timer.h"
#include "fdevent.h"
#include "wakeup_fd_event.h"
#include "../common/mutex.h"

namespace rocket {
  class EventLoop : public std::enable_shared_from_this<EventLoop> {
  public:
    typedef std::shared_ptr<EventLoop> ptr;
    EventLoop();
    ~EventLoop();

    void loop();
    void wakeUp();
    void stop();
    void addEpollEvent(FdEvent* event);
    void delEpollEvent(FdEvent* event);
    bool isInLoopThread() const;
    void addTask(std::function<void()>, bool is_wake_up = false);
    void addTimerEvent(TimerEvent::ptr event);
    bool isLooping() const { return _is_looping; }

    static EventLoop::ptr GetCurrentEventLoop();

  private:
    void dealWakeUp();
    void initWakeUpFdEvent();
    void initTimer();

  private:
    pid_t _thread_id {0};
    int _epoll_fd {0};
    int _wakeup_fd {0};
    bool _stop_flag {false};
    bool _is_looping {false};

    WakeUpFdEvent* _wakeup_fd_event {nullptr};
    Mutex _mutex{};

    std::set<int> _listen_fds;   // 当前监听的套接字
    std::queue<std::function<void()>> _pending_tasks;
    Timer::ptr _timer {};
  };
}
#endif //ROCKET_EVENTLOOP_H
